<?php

/**
 * invoice actions.
 *
 * @package    erp-crm
 * @subpackage invoice
 * @author     Milwell H. Sia
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class invoiceActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  
  private function getDaysDue($term_name){
    $c = new Criteria();
    $c->add(ListInvoiceTermsPeer::TERM,$term_name);
    $listInvoiceTerms = ListInvoiceTermsPeer::doSelectOne($c);
    return $listInvoiceTerms->getDays();
  }
  
  public function executeIndex(sfWebRequest $request){}
  
  public function executeCreate(sfWebRequest $request)
  {
    $contact_iden = $request->getParameter('contact_iden');
    $this->contact = ContactPeer::retrieveByPk($contact_iden);
    $this->forward404Unless($this->contact && $this->contact->getAccountCustomer());
    $this->documentForm = new DocumentForm();
    $this->invoiceForm = new InvoiceForm();
    
    $this->invoiceForm->setDefault('invoice_name',$this->contact->getListName());
    $this->invoiceForm->setDefault('terms_name',$this->contact->getAccountCustomer()->getDefaultTerms());
    $this->invoiceForm->setDefault('customer_iden',$this->contact->getIden());
    $this->invoiceForm->setDefault('vat_excempt_type',$this->contact->getAccountCustomer()->getDefaultTerms());
    $this->documentForm->setDefault('owner_iden',$this->contact->getAccountCustomer()->getDefaultOwnerIden());
    
    if(sfConfig::get('mod_invoice_number_auto'))
      $this->invoiceForm->setIdReadOnly();
    
    $this->error_message = '';
    
    $this->invoiceAmountsForm = new InvoiceAmountsForm();
    $this->invoice_amountss = array();
  }
  
  public function executeInsert(sfWebRequest $request){
    $invoice_iden = myStringGenerator::getIden();
    $amount_iden = myStringGenerator::getIden();
    $document_params = $request->getParameter('document');
    $document_params['document_iden'] = $invoice_iden;
    $document_params['document_type'] = 'INVOICE';
    $document_params['void'] = 'N';
    $document_params['void_date'] = null;
    $invoice_params = $request->getParameter('invoice');
    $invoice_params['invoice_iden'] = $invoice_iden;
    $invoice_params['days_due'] = $this->getDaysDue($invoice_params['terms_name']);
    $invoice_amounts_params = $request->getParameter('invoice_amounts');
    $invoice_amounts_params['invoice_iden'] = $invoice_iden;
    $invoice_amounts_params['amount_iden'] = $amount_iden;
    $this->documentForm = new DocumentForm();
    $this->invoiceForm = new InvoiceForm();
    $this->invoiceAmountsForm = new InvoiceAmountsForm();
    $this->documentForm->bind($document_params);
    $this->invoiceForm->setIssueDate($this->documentForm->getValue('document_date'));
    if((sfConfig::get('mod_invoice_number_auto'))&&(! $invoice_params['invoice_id'])){
      $invoice_id = ListDocumentTypesPeer::getNextId('INVOICE',$invoice_params['invoice_type']);
      if ($invoice_id){
        $invoice_params['invoice_id'] = vsprintf(sfConfig::get('mod_invoice_number_format'),$invoice_id);
        $this->invoiceForm->setIdTypeReadOnly();
      }
    }
    $this->invoiceForm->bind($invoice_params);
    $this->invoiceAmountsForm->bind($invoice_amounts_params);
    if((sfConfig::get('mod_invoice_number_strict'))&&($this->isUnique(null,$invoice_params['invoice_type'],$invoice_params['invoice_id'])>0)){
      $customer_iden = $invoice_params['customer_iden'];
      $this->contact = ContactPeer::retrieveByPk($customer_iden);
      $this->invoiceForm->setCustomerDefaults($this->contact);
      $this->error_message = $invoice_params['invoice_type'].'-'.$invoice_params['invoice_id'].' already exists.';
      return $this->setTemplate('create');
    }
    if(!($this->documentForm->isValid() && $this->invoiceForm->isValid() && $this->invoiceAmountsForm->isValid())){
      $customer_iden = $invoice_params['customer_iden'];
      $this->contact = ContactPeer::retrieveByPk($customer_iden);
      $this->invoiceForm->setCustomerDefaults($this->contact);
      $this->error_message = '';
      return $this->setTemplate('create');
    }
      $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
      $con->beginTransaction();
      try{
        $this->documentForm->save();
        $this->invoiceForm->save();
        $this->invoiceAmountsForm->save();
        $log_transaction = new LogTransaction();
        $log_transaction->setTransactionType('INVOICE');
        $log_transaction->setType1('CLIENT');
        $log_transaction->setIden1($this->invoiceForm->getObject()->getCustomerIden());
        $log_transaction->setType2('INVOICE');
        $log_transaction->setIden2($this->invoiceForm->getObject()->getInvoiceIden());
        $log_transaction->setType3('AMOUNT');
        $log_transaction->setIden3($this->invoiceAmountsForm->getObject()->getAmountIden());
        $log_transaction->setDebit($this->invoiceAmountsForm->getObject()->getSubTotal());
        $log_transaction->setDocumentIden($invoice_iden);
        $log_transaction->save();
        $con->commit();
        $this->redirect('invoice/edit?invoice_iden='.$this->invoiceForm->getObject()->getInvoiceIden());
      }catch(Exception $e){
        $con->rollBack();
        $request->getParameterHolder()->set('message',$e->getMessage());
        $this->forward('main','error');
      }
  }
  
  public function executeEdit(sfWebRequest $request){
    $document = DocumentPeer::retrieveByPk($request->getParameter('invoice_iden'));
    $invoice = InvoicePeer::retrieveByPk($request->getParameter('invoice_iden'));
    $this->forward404Unless(($document && $invoice));
    $this->documentForm = new DocumentForm($document);
    $this->invoiceForm = new InvoiceForm($invoice);
    $this->invoiceAmountsForm = new InvoiceAmountsForm();
    $this->invoiceAmountsForm->setDefault('invoice_iden',$invoice->getInvoiceIden());
    $this->contact = $invoice->getContact();
    $this->invoiceAmountss = $invoice->getInvoiceAmountss();
    
    if(sfConfig::get('mod_invoice_number_auto'))
      $this->invoiceForm->setIdTypeReadOnly();
      
    $this->error_message = '';
    
    $this->setLayout(false);
  }
  
  public function executeUpdate($request){
    $document_params = $request->getParameter('document');
    $invoice_params = $request->getParameter('invoice');
    $invoice_amounts_params = $request->getParameter('invoice_amounts');
    $invoice = InvoicePeer::retrieveByPk($invoice_params['invoice_iden']);
    $this->forward404Unless($invoice);
    $document = $invoice->getDocument();
    $document_params['owner_iden'] = $document->getOwnerIden();
    $this->forward404Unless($document);
    $this->documentForm = new DocumentForm($document);
    $this->invoiceForm = new InvoiceForm($invoice);
    $document_params['document_type'] = 'INVOICE';
    $document_params['void'] = 'N';
    $document_params['void_date'] = null;
    $invoice_params['days_due'] = $this->getDaysDue($invoice_params['terms_name']);
    $this->documentForm->bind($document_params);
    $this->invoiceForm->setIssueDate($this->documentForm->getValue('document_date'));
    $this->invoiceForm->bind($invoice_params);
    $this->invoiceAmountsForm = new InvoiceAmountsForm();
    $has_amounts = false;
    $old_subtotal = 0;
    if($invoice_amounts_params['description']!=''){
      if(($invoice_amounts_params['amount_iden']!='')&&($invoice_amounts_params['amount_iden']!='X')){
        $invoiceAmounts = InvoiceAmountsPeer::retrieveByPk($invoice_amounts_params['invoice_iden'],$invoice_amounts_params['amount_iden']);
        $this->forward404Unless($invoiceAmounts);
        $old_subtotal = $invoiceAmounts->getSubTotal();
        $this->invoiceAmountsForm = new InvoiceAmountsForm($invoiceAmounts);
      }else{
        $invoice_amounts_params['amount_iden'] = myStringGenerator::getIden();
        $this->invoiceAmountsForm = new InvoiceAmountsForm();
      }
      $this->invoiceAmountsForm->bind($invoice_amounts_params);
      $has_amounts = true;
    }
    $this->error_message = '';
    if((sfConfig::get('mod_invoice_number_strict'))&&($this->isUnique($invoice_params['invoice_iden'],$invoice_params['invoice_type'],$invoice_params['invoice_id'])>0)){
      $this->contact = $invoice->getContact();
      $this->invoiceAmountss = $invoice->getInvoiceAmountss();
      $this->setLayout(false);
      $this->error_message = $invoice_params['invoice_type'].'-'.$invoice_params['invoice_id'].' already exists.';
      return $this->setTemplate('edit');
    }
    if($has_amounts){
      if(($this->invoiceForm->isValid())&&($this->documentForm->isValid())&&($this->invoiceAmountsForm->isValid())){
        $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
        $con->beginTransaction();
        try{
          $this->documentForm->save();
          $this->invoiceForm->save();
          $new_amount = $this->invoiceAmountsForm->isNew();
          $this->invoiceAmountsForm->save();
          $log_transaction = new LogTransaction();
          $log_transaction->setTransactionType('INVOICE');
          $log_transaction->setType1('CLIENT');
          $log_transaction->setIden1($this->invoiceForm->getObject()->getCustomerIden());
          $log_transaction->setType2('INVOICE');
          $log_transaction->setIden2($this->invoiceForm->getObject()->getInvoiceIden());
          $log_transaction->setType3('AMOUNT');
          $log_transaction->setIden3($this->invoiceAmountsForm->getObject()->getAmountIden());
          if($new_amount)
            $log_transaction->setDebit($this->invoiceAmountsForm->getObject()->getSubTotal());
          else{
            if($old_subtotal > $this->invoiceAmountsForm->getObject()->getSubTotal())
              $log_transaction->setCredit($old_subtotal - $this->invoiceAmountsForm->getObject()->getSubTotal());
            else
              $log_transaction->setDebit($this->invoiceAmountsForm->getObject()->getSubTotal()-$old_subtotal);
          }
          $log_transaction->setDocumentIden($invoice->getInvoiceIden());
          $log_transaction->save();
          $con->commit();
          return $this->redirect('invoice/edit?invoice_iden='.$this->invoiceForm->getObject()->getInvoiceIden());
        }catch(Exception $e){
          $con->rollBack();
          $request->getParameterHolder()->set('message',$e->getMessage());
          return $this->forward('main','error');
        }
      }
    }else{
      if(($this->invoiceForm->isValid())&&($this->documentForm->isValid())){
        $this->documentForm->save();
        $this->invoiceForm->save();
        return $this->redirect('invoice/edit?invoice_iden='.$this->invoiceForm->getObject()->getInvoiceIden());
      }
    }
    if ($this->invoiceAmountsForm->isNew()){
      $invoice_amounts_params['amount_iden'] = 'X';
      $this->invoiceAmountsForm->bind($invoice_amounts_params);
    }
    $this->contact = $invoice->getContact();
    $this->invoiceAmountss = $invoice->getInvoiceAmountss();
    $this->setLayout(false);
    $this->setTemplate('edit');
  }
  
  
  public function executeVoid(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $this->invoice = InvoicePeer::retrieveByPk($invoice_iden);
    $this->forward404Unless($this->invoice);
    $document = $this->invoice->getDocument();
    $document->void();
    return $this->renderText(json_encode(array('invoice_iden'=>$invoice_iden,)));
  }
  
  public function executeSearch(sfWebRequest $request){
    $this->myInvoiceSearchForm = new myInvoiceSearchForm();
  }
  
  public function executeDoSearch(sfWebRequest $request){
      $myInvoiceSearchForm = new myInvoiceSearchForm();
      $myInvoiceSearchForm->bind($request->getParameter('skey_invoice'));
      $c = new Criteria();
      $c->addJoin(DocumentPeer::DOCUMENT_IDEN,InvoicePeer::INVOICE_IDEN);
      if($myInvoiceSearchForm['invoice_type']->getValue())
        $c->addAnd(InvoicePeer::INVOICE_TYPE,$myInvoiceSearchForm['invoice_type']->getValue());
      if($myInvoiceSearchForm['invoice_id_from']->getValue())
        $c->addAnd(InvoicePeer::INVOICE_ID,$myInvoiceSearchForm['invoice_id_from']->getValue(),Criteria::GREATER_EQUAL);
      if($myInvoiceSearchForm['invoice_id_to']->getValue())
        $c->addAnd(InvoicePeer::INVOICE_ID,$myInvoiceSearchForm['invoice_id_to']->getValue(),Criteria::LESS_EQUAL);
      $issue_date_from = $myInvoiceSearchForm['issue_date_from']->getValue();
      if(($issue_date_from['year'])&&($issue_date_from['month'])&&($issue_date_from['day'])){
        $issue_date_from_str = $issue_date_from['year'].'-'.$issue_date_from['month'].'-'.$issue_date_from['day'];
        $c->addAnd(DocumentPeer::DOCUMENT_DATE,$issue_date_from_str,Criteria::GREATER_EQUAL);
      }
      $issue_date_to = $myInvoiceSearchForm['issue_date_to']->getValue();
      if(($issue_date_to['year'])&&($issue_date_to['month'])&&($issue_date_to['day'])){
        $issue_date_to_str = $issue_date_to['year'].'-'.$issue_date_to['month'].'-'.$issue_date_to['day'];
        $c->addAnd(DocumentPeer::DOCUMENT_DATE,$issue_date_to_str,Criteria::LESS_EQUAL);
      }
      if($myInvoiceSearchForm['customer_name']->getValue()){
        $c->addJoin(ContactPeer::IDEN,InvoicePeer::CUSTOMER_IDEN);
        $c->add(ContactPeer::LIST_NAME,'%'.$myInvoiceSearchForm['customer_name']->getValue().'%',Criteria::LIKE);
      }
      if($myInvoiceSearchForm['show_void_only']->getValue()!='Y')
        $c->add(DocumentPeer::VOID,'N');
      else
        $c->add(DocumentPeer::VOID,'Y');
      $c->addAscendingOrderByColumn(InvoicePeer::INVOICE_TYPE);
      $c->addAscendingOrderByColumn(InvoicePeer::INVOICE_ID);
      $this->invoices = InvoicePeer::doSelect($c);
  }
  
  public function executeGetInvoiceTd(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $invoice = InvoicePeer::retrieveByPk($invoice_iden);
    return $this->renderPartial('invoice_grid_td',array('invoice'=>$invoice,));
  }
  
  public function executeEditInvoiceAmounts(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $amount_iden = $request->getParameter('amount_iden');
    $invoiceAmounts = InvoiceAmountsPeer::retrieveByPk($invoice_iden,$amount_iden);
    $this->forward404Unless($invoiceAmounts);
    $invoiceAmountsForm = new InvoiceAmountsForm($invoiceAmounts);
    return $this->renderPartial('invoice_amount_form',array('invoiceAmountsForm'=>$invoiceAmountsForm,));
  }
   
  public function executeShowInvoiceAmounts(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $this->invoice = InvoicePeer::retrieveByPk($invoice_iden);
    $this->forward404Unless($this->invoice);
    $this->invoiceAmountss = $this->invoice->getInvoiceAmountss();
    $this->setLayout(false);
  }
  
  public function executeDeleteInvoiceAmounts(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $amount_iden = $request->getParameter('amount_iden');
    $invoiceAmounts = InvoiceAmountsPeer::retrieveByPk($invoice_iden,$amount_iden);
    $invoiceAmounts->delete();
    return $this->renderText(json_encode(array('invoice_iden'=>$invoice_iden,)));
  }
  
  public function executeCreateInvoiceAmounts(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $invoiceAmountsForm = new InvoiceAmountsForm();
    $invoiceAmountsForm->setDefault('invoice_iden',$invoice_iden);
    return $this->renderPartial('invoice_amount_form',array('invoiceAmountsForm'=>$invoiceAmountsForm,));
  }
  
  public function executeGetInvoiceAmounts(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $c = new Criteria();
    $c->add(InvoiceAmountsPeer::INVOICE_IDEN,$invoice_iden);
    $c->addAscendingOrderByColumn(InvoiceAmountsPeer::DESCRIPTION);
    $invoiceAmountss = InvoiceAmountsPeer::doSelect($c);
    return $this->renderPartial('invoice_amount_grid',array('invoiceAmountss'=>$invoiceAmountss,));
  }
  
  public function executeListBalance(sfWebRequest $request){
    $customer_iden = $request->getParameter('customer_iden');
    $owner_iden = $request->getParameter('owner_iden');
    $this->click_callback = $request->getParameter('click_callback');
    $con = Propel::getConnection();
    $this->receivables = myQuery::getReceivables($con,$customer_iden,$owner_iden);
  
  }
  
  private function isUnique($invoice_iden,$invoice_type,$invoice_id){
    $c = new Criteria();
    if ($invoice_iden)
      $c->addAnd(InvoicePeer::INVOICE_IDEN,$invoice_iden,Criteria::NOT_EQUAL);
    $c->addAnd(InvoicePeer::INVOICE_TYPE,$invoice_type);
    $c->addAnd(InvoicePeer::INVOICE_ID,$invoice_id);
    $c->addJoin(DocumentPeer::DOCUMENT_IDEN,InvoicePeer::INVOICE_IDEN);
    $c->addAnd(DocumentPeer::VOID,'N');
    return InvoicePeer::doCount($c);
  }
  
  public function executeCheckId(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $invoice_type = $request->getParameter('invoice_type');
    $invoice_id = $request->getParameter('invoice_id');
    $count = $this->isUnique($invoice_iden,$invoice_type,$invoice_id);
    return $this->renderText(json_encode(array('count'=>$count,)));
  }
  
  public function executeCanVoid(sfWebRequest $request){
    $invoice_iden = $request->getParameter('invoice_iden');
    $invoice = InvoicePeer::retrieveByPk($invoice_iden);
    $transaction = $invoice->getTransactions();
    if(($transaction['DEBIT MEMO']>0)||($transaction['CREDIT MEMO']<0)||($transaction['PAYMENT']<0)||($transaction['OTHERS']!=0)){
      $message = 'Cannot void, invoice has: ';
      if ($transaction['DEBIT MEMO']>0)
        $message .= 'Debit Memo, ';
      if ($transaction['CREDIT MEMO']<0)
        $message .= 'Credit Memo, ';
      if ($transaction['PAYMENT']<0)
        $message .= 'Payment, ';
      if ($transaction['OTHERS']!=0)
        $message .= 'Others, ';
      return $this->renderText(json_encode(array('success'=>false,'message'=>$message,)));
    }else
      return $this->renderText(json_encode(array('success'=>true,)));
  }
  
}
